package cn.agiledata.bank.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @author mxb
 * 
 */
public class HttpTookit implements java.io.Serializable {

	private static Log log = LogFactory.getLog(HttpTookit.class);

	/**
	 * 执行一个HTTP GET请求，返回请求响应的HTML
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param queryString
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @param pretty
	 *            是否美化
	 * @return 返回请求响应的HTML
	 */
	public static String doGet(String url, String queryString, String charset,
			boolean pretty) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		try {
			if (StringUtils.isNotBlank(queryString))
				// 对get请求参数做了http请求默认编码，好像没有任何问题，汉字编码后，就成为%式样的字符串
				method.setQueryString(URIUtil.encodeQuery(queryString));
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(method.getResponseBodyAsStream(),
								charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty)
						response.append(line).append(
								System.getProperty("line.separator"));
					else
						response.append(line);
				}
				reader.close();
			}
		} catch (URIException e) {
			log.error("执行HTTP Get请求时，编码查询字符串“" + queryString + "”发生异常！", e);
		} catch (IOException e) {
			log.error("执行HTTP Get请求" + url + "时，发生异常！", e);
		} finally {
			method.releaseConnection();
		}
		return response.toString();
	}
	
	public static String doGet(String url, Map<String, String> params, String charset,
			boolean pretty) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		String result = null;
		try {
			// 判断是否有map参数，如果有自动附加到url后
			NameValuePair parametes[]=new NameValuePair[params.size()];
			// 设置Http Post数据
			NameValuePair pram = null;
			if (params != null) {
				int i=0;
				for (Map.Entry<String, String> entry : params.entrySet()) {
					System.out.println("****************传递参数开始****************");
					System.out.println(entry.getKey()+":"+ entry.getValue());
					System.out.println("****************传递参数结束****************");
					pram = new NameValuePair();
					pram.setName(entry.getKey());
					pram.setValue(entry.getValue());
					parametes[i]=pram;
					i++;
				}
				method.setQueryString(parametes);
			}
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(method.getResponseBodyAsStream(),
								charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty)
						response.append(line).append(
								System.getProperty("line.separator"));
					else
						response.append(line);
				}
				reader.close();
			}
		} catch (URIException e) {
			log.error("执行HTTP Get请求时，编码查询字符串发生异常！", e);
		} catch (IOException e) {
			log.error("执行HTTP Get请求" + url + "时，发生异常！", e);
		} finally {
			if(response != null && response.toString().toLowerCase().indexOf("0000") >= 0)
			{
				result="true";
			}
			method.releaseConnection();
		}
		System.out.println("****************返回结果****************");
		System.out.println(response);
		System.out.println("****************返回结果****************");
		return result;
	}

	/**
	 * 执行一个HTTP POST请求，返回请求响应的HTML
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param params
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @param pretty
	 *            是否美化
	 * @return 返回请求响应的HTML
	 */
	public static String doPost(String url, Map<String, String> params,
			String charset, boolean pretty) {
		String result="false";
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		
		NameValuePair parametes[]=new NameValuePair[params.size()];
		// 设置Http Post数据
		NameValuePair pram = null;
		if (params != null) {
			int i=0;
			for (Map.Entry<String, String> entry : params.entrySet()) {
				pram = new NameValuePair();
				pram.setName(entry.getKey());
				pram.setValue(entry.getValue());
				parametes[i]=pram;
			i++;
			}
		}
		try {
				
				method.setRequestBody(parametes);   
				//method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
		        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);
				//method.addRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=" + charset); 
				method.addRequestHeader("Content-Type","textml; charset" + charset); 
				
				client.executeMethod(method);  
				method.getStatusCode();
				String responseStr=method.getResponseBodyAsString().replace(" ", "").toLowerCase();
				
				System.out.println("****************商户页面输出内容开始****************");
				System.out.println(responseStr);
				System.out.println("****************商户页面输出内容结束****************");
				
				if(responseStr.indexOf("0000")!=-1)
				{
					result="true";
				}
		       method.releaseConnection();    
		} catch (IOException e) {
			log.error("执行HTTP Post请求" + url + "时，发生异常！", e);
		} finally {
			method.releaseConnection();
		}
		return result;

	}
	public static String doPost2(String url, Map<String, String> params,
			String charset, boolean pretty) {
		String result="false";
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		
		NameValuePair parametes[]=new NameValuePair[params.size()];
		// 设置Http Post数据
		NameValuePair pram = null;
//		if (params != null) {
//			int i=0;
//			for (Map.Entry<String, String> entry : params.entrySet()) {
//				pram = new NameValuePair();
//				pram.setName(entry.getKey());
//				pram.setValue(entry.getValue());
//				parametes[i]=pram;
//			i++;
//			}
//		}
		Document document=null;
		if (params != null) {
			document = DocumentHelper.createDocument();	
			Element smd=document.addElement("shortMessageDto");
		for (Map.Entry<String, String> entry : params.entrySet()) {
			Element et=smd.addElement(entry.getKey());
			et.setText(entry.getValue());
		}
	   }
		try {
				
			    RequestEntity requestEntity = new StringRequestEntity(document.asXML(), "application/xml",charset);
			    method.setRequestEntity(requestEntity);
		        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);
				//method.addRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=" + charset); 
				method.addRequestHeader("Content-Type","application/xml; charset" + charset); 
				
				client.executeMethod(method);  
				method.getStatusCode();
				String responseStr=method.getResponseBodyAsString().replace(" ", "").toLowerCase();
				
				System.out.println("****************商户页面输出内容开始****************");
				System.out.println(responseStr);
				System.out.println("****************商户页面输出内容结束****************");
				
				if(responseStr.indexOf("00")!=-1)
				{
					result="true";
				}
		       method.releaseConnection();    
		} catch (IOException e) {
			log.error("执行HTTP Post请求" + url + "时，发生异常！", e);
		} finally {
			method.releaseConnection();
		}
		return result;

	}

/*	public static void main(String[] args) {

		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost("localhost", 8989);
		PostMethod post = new PostMethod(
				"http://localhost:8989");
		NameValuePair name = new NameValuePair("server", "ld");
		NameValuePair pass = new NameValuePair("mac", "ld");
		post.setRequestBody(new NameValuePair[] { name, pass });
		try {
			int status = client.executeMethod(post);
			System.out.println(status);
		} catch (HttpException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		
		post.releaseConnection();
		
		URLConnection connection;
		try {
			connection = new URL("http://localhost:8989/service/index.jsp").openConnection();
			connection.setDoOutput(true);
			OutputStreamWriter writer = new OutputStreamWriter(connection
					.getOutputStream());
			writer.write("returncode=true");
			writer.flush();
			writer.close();
			BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
			StringBuffer sBuffer = new StringBuffer();
			String tempStr;
			byte[] b = new byte[1024];
			int i = 0;
			while ((i = bis.read(b)) > 0) {
				tempStr = new String(b, 0, i);
				sBuffer.append(tempStr);
			}
			String responseStr=sBuffer.toString();
			System.out.println(responseStr.indexOf("<metaname=\"pubpay\"content=\"true\">"));
			System.out.println(sBuffer.toString());
			
		} catch (MalformedURLException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		

	}*/
	

}
